import Negotiator from 'negotiator';
import {NextRequest, NextResponse} from 'next/server';
import {match} from '@formatjs/intl-localematcher';
import {SUPPER_LANGUAGE} from '@/config/language';
import {DEFAULT_PATH} from '@/config/router';

export function middleware(request: NextRequest) {
    const {pathname} = request.nextUrl;

    // 处理静态资源
    if (pathname.startsWith('/tk/')) {
        return NextResponse.rewrite(new URL(pathname.replace(/^\/tk/, ''), request.url));
    }

    // 处理api
    if (pathname.startsWith('/api/')) {
        return NextResponse.next();
    }

    // 如果传入了支持的语言，直接跳转
    const requestHeaders = new Headers(request.headers);
    const pathnameLocale = SUPPER_LANGUAGE.find(
        locale => pathname.startsWith(`/${locale}`) || pathname === `/${locale}`
    );
    if (pathnameLocale) {
        request.headers.set('Language', pathnameLocale);
        if (`/${pathnameLocale}` === pathname) {
            request.nextUrl.pathname = `/${pathnameLocale}/${DEFAULT_PATH[1]}`;
            return NextResponse.redirect(request.nextUrl);
        }

        requestHeaders.set('Language', pathnameLocale);
        return NextResponse.next(
            {request: {headers: requestHeaders}}
        );
    }

    // 匹配请求头中的语言
    const headers = {'accept-language': requestHeaders.get('accept-language') || ''};
    const languages = new Negotiator({headers}).languages();
    const locale = match(languages, SUPPER_LANGUAGE, 'en');

    request.nextUrl.pathname = `/${locale}${pathname === '/' ? `/${DEFAULT_PATH[1]}` : pathname}`;
    request.headers.set('Language', locale);
    return NextResponse.redirect(request.nextUrl);
}

export const config = {
    matcher: ['/((?!favicon.ico).*)']
};
